package com.lagou.utils;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: spring
 * @description:
 * @author: Mr.Wang
 * @create: 2020-12-15 11:06
 **/
public class BeanFactory {
	private static Map<String,Object> classMap = new HashMap<>();
	static {
		InputStream resourceStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(resourceStream);
			List<Element> list = document.selectNodes("//bean");
			for (Element element : list) {
				String id = element.attributeValue("id");
				String className = element.attributeValue("class");
				Object o = Class.forName(className).newInstance();
				classMap.put(id,o);
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Object getBean(String beanId){
		return classMap.get(beanId);
	}
}
